package org.example.sysdept.service.impl;

import org.example.Exception.SysDeptException;
import org.example.sysdept.entity.SysDept;
import org.example.sysdept.mapper.SysDeptMapper;
import org.example.sysdept.service.SysDeptService;

import java.util.List;
import java.util.Objects;

public class SysDeptServiceImpl implements SysDeptService {
    private SysDeptMapper sysDeptMapper;
    @Override
    public int insertSysDept(SysDept sysDept) {
        if(Objects.isNull(sysDept)){
            throw new SysDeptException("部门不能为空");
        }
        String deptName = sysDept.getDeptName();
        if (deptName == null || deptName.trim().isEmpty()) {
            throw new SysDeptException("部门名称不能为空");
        }
        Long parentId = sysDept.getParentId();
        if (parentId == null || parentId==0) {
            throw new SysDeptException("上级部门不能为空");
        }
        SysDeptMapper sysDeptMapper = new SysDeptMapper();
        List list=sysDeptMapper.selectSysDeptList(sysDept);
        if (list != null && !list.isEmpty()) {
            throw new RuntimeException("该父级部门下已存在同名部门，禁止重复新增");
        }
        return sysDeptMapper.insertSysDept(sysDept);
    }

    @Override
    public List<SysDept> selectSysDeptList(SysDept sysDept) {
        sysDeptMapper=new SysDeptMapper();
        return sysDeptMapper.selectSysDeptList(sysDept);
    }

    /**
     * 删除部门
     * @param deptId
     * @return
     */
    @Override
    public int deleteSysDept(Long deptId) {
        sysDeptMapper=new SysDeptMapper();
        if(deptId==null){
            throw new SysDeptException("部门id不能为空");
        }
        SysDept sysDept=new SysDept();
        sysDept.setParentId(deptId);
        List list=sysDeptMapper.selectSysDeptList(sysDept);
        if (list!=null && !list.isEmpty()){
            throw new SysDeptException("部门下有子部门，请先删除子部门");
        }

        return sysDeptMapper.deleteSysDept(deptId);
    }
    @Override
    public int updateSysDept(SysDept sysDept) {
        if (sysDept.getDeptId()==null){
            throw new SysDeptException("部门id不能为空");
        }
        List  list=sysDeptMapper.selectSysDeptList(sysDept);
        System.out.println( list);
        if (list!=null && !list.isEmpty()){
            throw new SysDeptException("该部门已存在");
        }
        return sysDeptMapper.updateSysDept(sysDept);
    }

    @Override
    public SysDept selectSysDept(Long deptId) {
        sysDeptMapper=new SysDeptMapper();
        if (deptId==null){
            throw new SysDeptException("部门id不能为空");
        }
        return sysDeptMapper.selectSysDept(deptId);
    }
}
